from django.shortcuts import render
from django.http import JsonResponse
from django.views import View
from apps.areas.models import Area
import logging
from django.core.cache import cache

logger = logging.getLogger('django')


class AreasView(View):
    """省市区数据"""

    def get(self, request):
        """提供省市区数据"""

        # 提供省份数据
        # 检查是否有缓存数据
        province_list = cache.get('province')
        if province_list is None:
            # 如果没有，查询数据库，并且缓存

            try:
                # 查询省份数据
                province_model_list = Area.objects.filter(parent__isnull=True)
                # 序列化省级数据
                province_list = []
                for province_model in province_model_list:
                    province_list.append({'id': province_model.id, 'name': province_model.name})
                    cache.set('province', province_list, 24 * 3600)
            except Exception as e:
                logger.error(e)
                return JsonResponse({'code': 400, 'errmsg': '省份数据错误'})
        # 响应省份数据
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'province_list': province_list})


class SubAreasView(View):
    """省市区数据"""

    def get(self, request, id):
        """提供省市区数据"""
        # 提供市或区数据
        # 获取缓存数据
        # 新特性 f 相当于format
        data_list = cache.get(f'city:{id}')
        # data_list = cache.get('city:{}'.format(id))
        if data_list is None:
            try:
                up_level = Area.objects.get(id=id)  # 查询市或区的父级
                down_level = up_level.subs.all()
                # 序列化市或区数据
                data_list = []
                for item in down_level:
                    data_list.append({'id': item.id, 'name': item.name})
                # sub_data = {
                #     'id': parent_model.id,  # 父级pk
                #     'name': parent_model.name,  # 父级name
                # }
                cache.set(f'city:{id}', data_list,24*3600)
            except Exception as e:
                logger.error(e)
                return JsonResponse({'code': 400, 'errmsg': '城市或区数据错误'})
        # 响应市或区数据
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'sub_data': {'subs': data_list}})
